package com.aixs.crud.contorller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;


@Controller
@RequestMapping("/files")
public class FileUploadController {
	@Autowired
	private HttpServletRequest request;
	@RequestMapping("filesUpload")
	public void filesUpload(@RequestParam("files") MultipartFile[] files) {
		if(files!=null&&files.length>0){
			for(int i = 0;i<files.length;i++){
				MultipartFile file = files[i];
				saveFile(file);
			}
		}
		/*return "filesUpload";*/
	}

	/***
	 * @param file
	 * @return
	 */
	private boolean saveFile(MultipartFile file) {
		if (!file.isEmpty()) {
			try {
				String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
						+ file.getOriginalFilename();
				file.transferTo(new File(filePath));
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	/***
	 *
	 * @param file
	 * @return
	 */
	@RequestMapping("fileUpload")
	public String fileUpload(@RequestParam("file") MultipartFile file) {
		System.out.printf("666666");
		if (!file.isEmpty()) {
			try {
				String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"
						+ file.getOriginalFilename();
				file.transferTo(new File(filePath));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return "redirect:/index.jsp";
	}

	/***
	 *
	 * @return
	 */
	@RequestMapping("list")
	public ModelAndView list() {
		String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/";
		ModelAndView mav = new ModelAndView("list");
		File uploadDest = new File(filePath);
		String[] fileNames = uploadDest.list();
		for (int i = 0; i < fileNames.length; i++) {
			System.out.println(fileNames[i]);
		}
		return mav;
	}
}
